package org.zkoss.zktc.core.groovy

import groovy.lang.MissingPropertyException;

import java.util.Collection;

import org.openqa.selenium.WebElement;
import org.zkoss.zktc.core.widget.*;

class DynamicMethods{
	static {
		Widget.metaClass.methodMissing = {name,args ->
			if(name.equals("find")){
				def fn = Widget.metaClass?.getMetaMethod("findWidget",args);
				if(fn) return widget = fn.invoke(delegate,args);
			}
			if(name.equals("finds")){
				def fn = Widget.metaClass?.getMetaMethod("findWidgets",args);
				if(fn) return widget = fn.invoke(delegate,args);
			}
			throw new MissingMethodException(name, getClass(),args)
		}
		
		Widget.metaClass.propertyMissing = {name ->
			def attr = delegate.getAttribute(name);
			return attr;
		}
		
		WebElement.metaClass.propertyMissing = {name ->
			if(name.equals("uuid")){
				return delegate.getAttribute("id");
			}
			def attr = delegate.getAttribute(name);
			return attr;
		}
		
		Collection.metaClass.toUuid = {
			def r = []
			delegate.each{
				if(it instanceof Widget || it instanceof WebElement 
					|| it?.metaClass?.getMetaProperty("uuid")){
					r << it.uuid;
				}else{
					r << "";
				}
			}
			return r;
		}
		Collection.metaClass.toId = {
			def r = []
			delegate.each{
				if(it instanceof Widget || it?.metaClass?.getMetaProperty("id")){
					r << it.id;
				}else{
					r << "";
				}
			}
			return r;
		}
	}
}

//DynamicMethods.apply()